﻿using System.Data.SqlClient;
using Dapper;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
using PLM.ConfigurationCenter.Model;

namespace PLM.ConfigurationCenter.Backup.Handle {
    public class Common {
        /// <summary>
        /// 检查数据库连接
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool CheckHealth(TaskModel model, out string error) {
            error = "";
            try {
                string dbconn;
                if (model.DataBaseType == 1) {
                    dbconn = $"Data Source=localhost;Initial Catalog={model.DataBase};User ID={model.Username};Password={model.Password};";
                    string sql = " select '数据库连接成功' ";
                    using (var dbcontext = new SqlConnection(dbconn)) {
                        dbcontext.QueryFirst<string>(sql);
                    }
                } else if (model.DataBaseType == 2) {
                    dbconn = $"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=ORCL)));User Id={model.Username};Password={model.Password};";
                    string sql = " select '数据库连接成功' from dual ";
                    using (var dbcontext = new OracleConnection(dbconn)) {
                        dbcontext.QueryFirst<string>(sql);
                    }
                } else {
                    dbconn = $"PORT=5432;DATABASE={model.DataBase};HOST=localhost;PASSWORD={model.Password};USER ID={model.Username};";
                    string sql = " select '数据库连接成功' ";
                    using (var dbcontext = new NpgsqlConnection(dbconn)) {
                        dbcontext.QueryFirst<string>(sql);
                    }
                }
            } catch (Exception ex) {
                error = ex.Message;
                return false;
            }
            return true;
        }
    }
}
